package com.icoolkj.security.springmvc.service.impl;

import com.icoolkj.security.springmvc.dto.AuthenticationDTO;
import com.icoolkj.security.springmvc.service.AuthenticationService;
import com.icoolkj.security.springmvc.vo.UserVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author icoolkj
 * @version 1.0
 * @description 用户认证实现
 * @createDate 2025/02/06 22:11
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    /**
     * 校验用户认证信息是否合法
     * @param authenticationDTO
     * @return
     */
    @Override
    public UserVO authentication(AuthenticationDTO authenticationDTO) {
        // 校验参数是否为空
        if (authenticationDTO == null
                || StringUtils.isEmpty(authenticationDTO.getUsername())
                || StringUtils.isEmpty(authenticationDTO.getPassword())){
             throw new RuntimeException("账号和密码为空");
        }
        
        // 模拟数据库查询
        UserVO userVO = getUserVO(authenticationDTO.getUsername());

        // 判断用户是否为空
        if (userVO == null){
            throw new RuntimeException("查询不到该用户");
        }

        // 校验密码
        if(!authenticationDTO.getPassword().equals(userVO.getPassword())){
            throw new RuntimeException("账号或密码错误");
        }

        // 认证通过，返回用户信息
        return userVO;
    }

    private UserVO getUserVO(String username) {
        return userVOMap.get(username);
    }

    private Map<String, UserVO> userVOMap = new HashMap<>();
    {
        // 定义权限
        Set<String> authorities1 = new HashSet<>();
        authorities1.add("p1"); // 这个 p1 我们人为让它 和 r/r1 对应
        Set<String> authorities2 = new HashSet<>();
        authorities2.add("p2"); // 这个 p2 我们人为让它 和 r/r2 对应

        // 增加用户权限
        userVOMap.put("zhangsan", new UserVO("1", "zhangsan", "123", "张三", "15000000000", authorities1));
        userVOMap.put("lisi", new UserVO("2", "lisi", "678", "李四", "15888888888", authorities2));

    }


}
